//
//  mainView.m
//  SmartHome
//
//  Created by 赵嘉诚 on 15/3/15.
//  Copyright (c) 2015年 赵嘉诚. All rights reserved.
//

#import "mainView.h"
#import "floorTableViewCell.h"
#import "deviceView.h"
#import "TVView.h"
#import "curtainView.h"
#import "MBView.h"
#import "lightView.h"
#import "airView.h"
#import "STBView.h"
#import "DVDView.h"
#import "AMPView.h"

@interface mainView () <UITableViewDataSource, UITableViewDelegate, sendRespondProtocol>
{
    NSDictionary *functionList;
    NSInteger floorCount;
    NSInteger deviceCount;
    NSMutableArray *nowFloor;
    NSArray *nowRoom;
    NSMutableArray *nowDevice;
    NSMutableArray *nowOtherDevice;
    NSDictionary *jsonDic;
    NSInteger selectedwhichFloor;
    NSInteger selectedwhichRoom;
    NSDictionary *selectedDevice;
    NSString *floorName;
    NSString *roomName;
    NSString *deviceName;
    __weak UIView *nowView;
    BOOL isFloorView;
    NSArray *states;
}

@property (nonatomic, strong) UITableView *floorTableView;
@property (nonatomic, strong) deviceView *myDeviceView;
@property (nonatomic, strong) UITableView *otherDeviceTableView;

@property (nonatomic, strong) TVView *myTVView;
@property (nonatomic, strong) curtainView *myCurtainView;
@property (nonatomic, strong) MBView *myMBView;
@property (nonatomic, strong) lightView *myLightView;
@property (nonatomic, strong) airView *myAirView;
@property (nonatomic, strong) STBView *mySTBView;
@property (nonatomic, strong) DVDView *myDVDView;
@property (nonatomic, strong) AMPView *myAMPView;

@end

@implementation mainView

- (UITableView *)floorTableView
{
    if(!_floorTableView){
        _floorTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height - 70)
                                                      style:UITableViewStylePlain];
        _floorTableView.backgroundColor = BACKGROUND_COLOR;
        _floorTableView.tableFooterView = [[UIView alloc] init];
        _floorTableView.dataSource = self;
        _floorTableView.delegate = self;
    }
    return _floorTableView;
}

- (deviceView *)myDeviceView
{
    if(!_myDeviceView){
        _myDeviceView = [[deviceView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height - 70)];
        _myDeviceView.backgroundColor = BACKGROUND_COLOR;
        
        __weak mainView *m = self;
        _myDeviceView.showFundationView = ^(NSUInteger num){
            [m showFundationWithNumber:num];
        };
        _myDeviceView.pressResponse = ^(NSString *fundation, NSInteger row){
            [m pressFundation:fundation Row:row];
        };
    }
    return _myDeviceView;
}

- (UITableView *)otherDeviceTableView
{
    if(!_otherDeviceTableView){
        _otherDeviceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)
                                                             style:UITableViewStylePlain];
        _otherDeviceTableView.backgroundColor = BACKGROUND_COLOR;
        _otherDeviceTableView.tableFooterView = [[UIView alloc] init];
        _otherDeviceTableView.dataSource = self;
        _otherDeviceTableView.delegate =self;
    }
    return _otherDeviceTableView;
}

- (TVView *)myTVView
{
    if(!_myTVView){
        _myTVView = [[TVView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myTVView.backgroundColor = BACKGROUND_COLOR;
        _myTVView.delegate = self;
    }
    return _myTVView;
}

- (curtainView *)myCurtainView
{
    if(!_myCurtainView){
        _myCurtainView = [[curtainView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myCurtainView.backgroundColor = BACKGROUND_COLOR;
        _myCurtainView.delegate = self;
    }
    return _myCurtainView;
}

- (MBView *)myMBView
{
    if(!_myMBView){
        _myMBView = [[MBView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myMBView.backgroundColor = BACKGROUND_COLOR;
        _myMBView.delegate = self;
    }
    return _myMBView;
}

- (lightView *)myLightView
{
    if(!_myLightView){
        _myLightView = [[lightView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myLightView.backgroundColor = BACKGROUND_COLOR;
        _myLightView.delegate = self;
    }
    return _myLightView;
}

- (airView *)myAirView
{
    if(!_myAirView){
        _myAirView = [[airView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myAirView.backgroundColor = BACKGROUND_COLOR;
        _myAirView.delegate = self;
    }
    return _myAirView;
}

- (STBView *)mySTBView
{
    if(!_mySTBView){
        _mySTBView = [[STBView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _mySTBView.backgroundColor = BACKGROUND_COLOR;
        _mySTBView.delegate = self;
    }
    return _mySTBView;
}

- (DVDView *)myDVDView
{
    if(!_myDVDView){
        _myDVDView = [[DVDView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myDVDView.backgroundColor = BACKGROUND_COLOR;
        _myDVDView.delegate = self;
    }
    return _myDVDView;
}

- (AMPView *)myAMPView
{
    if(!_myAMPView){
        _myAMPView = [[AMPView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _myAMPView.backgroundColor = BACKGROUND_COLOR;
        _myAMPView.delegate = self;
    }
    return _myAMPView;
}

//分析json数据
- (void)analysisFloor
{
    NSArray *floorArray = [jsonDic objectForKey:@"FLOOR"];
    floorCount = [floorArray count];
    nowFloor = [[NSMutableArray alloc] initWithArray:floorArray];
    if(!states){
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int i = 0; i < floorCount; i++) {
            cellState *s = [[cellState alloc] init];
            s.state = NO;
            [array addObject:s];
        }
        states = array;
    }
}

- (void)analysisDevice
{
    NSDictionary *room = [nowRoom objectAtIndex:selectedwhichRoom];
    NSArray *deviceArray = [jsonDic objectForKey:@"DEVICE"];
    NSDictionary *device;
    nowDevice = [[NSMutableArray alloc] init];
    for (device in deviceArray) {
        if([[device objectForKey:@"roomName"] isEqualToString:[room objectForKey:@"roomName"]]){
            [nowDevice addObject:device];
        }
    }
    NSArray *otherArray = [jsonDic objectForKey:@"SENSOR"];
    nowOtherDevice = [[NSMutableArray alloc] init];
    for (device in otherArray) {
        if([[device objectForKey:@"roomName"] isEqualToString:[room objectForKey:@"roomName"]]){
            [nowOtherDevice addObject:device];
        }
    }
    deviceCount = [nowDevice count];
}

#pragma mark - UITableViewDataSource 协议
//对应第section组的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(isFloorView){
        [self analysisFloor];
    }else{
        [self analysisDevice];
    }
    if(tableView == self.floorTableView){
        return floorCount;
    }else{
        return nowOtherDevice.count;
    }
}

//组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//每一行的设置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIndentifier = @"Cell";
    floorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if(cell == nil){
        cell = [[floorTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
    }
    if(tableView == self.floorTableView){
        NSDictionary *floor = [nowFloor objectAtIndex:indexPath.row];
        NSString *floor_name = [floor objectForKey:@"floorName"];
        cell.label.text = floor_name;
        NSArray *rooms = [jsonDic objectForKey:@"ROOM"];
        NSMutableArray *myRooms = [[NSMutableArray alloc] init];
        for (NSDictionary *room in rooms) {
            if([[room objectForKey:@"floorName"] isEqualToString:floor_name]){
                [myRooms addObject:room];
            }
        }
        cell.dataArray = myRooms;
        __weak mainView *m = self;
        cell.selectCell = ^(NSInteger num, NSArray *data){
            [m selectRoom:num Data:data];
        };
        
        cellState *s = (cellState *)states[indexPath.row];
        s.count = myRooms.count;
        if(s.state){
            [cell showDetailCell];
        }else{
            [cell missDetailCell];
        }
        UIImageView *old_view = (UIImageView *)[cell viewWithTag:44];
        [old_view removeFromSuperview];
        UIImage *rightImage;
        if(cell.isShowDetailCell){
            rightImage = GET_IAMGE_WITH_NAME(@"Image/tableView/down");
        }else{
            rightImage = GET_IAMGE_WITH_NAME(@"Image/tableView/monitor_go");
        }
        UIImageView *rightImageView = [[UIImageView alloc] initWithImage:rightImage];
        [rightImageView setFrame:CGRectMake(cell.bounds.size.width - 40, 10, 30, 30)];
        rightImageView.tag = 44;
        [cell addSubview:rightImageView];
        cell.backgroundColor = TEXT_GRAY_COLOR;
    }else{
        cell.textLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:22];
        cell.textLabel.text = [[nowOtherDevice objectAtIndex:indexPath.row] objectForKey:@"sensorName"];
        UIImage *leftImage = GET_IAMGE_WITH_NAME(@"Image/tableView/list_lang");
        cell.imageView.image = leftImage;
        CGSize itemSize = CGSizeMake(30, 30);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
        [cell.imageView.image drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.backgroundColor = [UIColor whiteColor];
    }
    return cell;
}

//选择了相应行后的操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(tableView == self.floorTableView){
        selectedwhichFloor = indexPath.row;
        floorTableViewCell *cell = (floorTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        cellState *s = (cellState *)states[indexPath.row];
        if(cell.isShowDetailCell){
            [cell missDetailCell];
            s.state = NO;
        }else{
            [cell showDetailCell];
            s.state = YES;
        }
        [self.floorTableView reloadData];
    }else{
        NSDictionary *dic = [nowOtherDevice objectAtIndex:indexPath.row];
        NSString *sensorID = [dic objectForKey:@"sensorId"];
        NSString *codeType = [dic objectForKey:@"codeType"];
        NSString *freqType = [dic objectForKey:@"freqType"];
        NSString *message1 = [NSString stringWithFormat:@"PT%@_%@-SEND-",codeType,freqType];
        self.sendMessage(message1, sensorID);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cellState *s = (cellState *)states[indexPath.row];
    if(tableView == self.floorTableView){
        if(s.state){
            return 50 + s.count * 50;
        }else{
            return 50;
        }
    }
    return 75;
}

- (void)selectRoom:(NSInteger)num Data:(NSArray *)data
{
    selectedwhichRoom = num;
    nowRoom = data;
    roomName = [[nowRoom objectAtIndex:num] objectForKey:@"roomName"];
    [self.floorTableView removeFromSuperview];
    self.floorTableView = nil;

    [self analysisDevice];
    [self.myDeviceView showWithDeviceArray:nowDevice OtherArray:nowOtherDevice];
    [self.delegate showLeftButton];
    [self addSubview:self.myDeviceView];
    [self.delegate showTitle:roomName];
}

- (void)showFundationWithNumber:(NSUInteger)num
{
    if(num < deviceCount){
        selectedDevice = [nowDevice objectAtIndex:num];
        NSString *deviceType = [[nowDevice objectAtIndex:num] objectForKey:@"deviceType"];
        deviceName = [[nowDevice objectAtIndex:num] objectForKey:@"deviceName"];
        if([deviceType isEqualToString:TV_TYPE]){     //电视
            [self addSubview:self.myTVView];
            nowView = self.myTVView;
        }else if([deviceType isEqualToString:CURTAIN_TYPE]){     //窗帘
            [self addSubview:self.myCurtainView];
            nowView = self.myCurtainView;
        }else if([deviceType isEqualToString:MB_TYPE]){      //幕布
            [self addSubview:self.myMBView];
            nowView = self.myMBView;
        }else if([deviceType isEqualToString:LIGHT_TYPE1] || [deviceType isEqualToString:LIGHT_TYPE2] || [deviceType isEqualToString:LIGHT_TYPE3]){   //灯
            [self addSubview:self.myLightView];
            nowView = self.myLightView;
        }else if([deviceType isEqualToString:AIR_TYPE]){     //空调
            [self addSubview:self.myAirView];
            nowView = self.myAirView;
        }else if([deviceType isEqualToString:STB_TYPE]){     //机顶盒
            [self addSubview:self.mySTBView];
            nowView = self.mySTBView;
        }else if([deviceType isEqualToString:DVD_TYPE]){     //影碟机
            [self addSubview:self.myDVDView];
            nowView = self.myDVDView;
        }else if([deviceType isEqualToString:AMP_TYPE]){     //功放
            [self addSubview:self.myAMPView];
            nowView = self.myAMPView;
        }else if([deviceType isEqualToString:@"SX"]){     //摄像机

        }
        [self.delegate showTitle:deviceName];
    }else{
        [self addSubview:self.otherDeviceTableView];
        [self.delegate showTitle:@"其他"];
    }
    self.myDeviceView = nil;
    [self.myDeviceView removeFromSuperview];
    [self.delegate hideTabView];
}

- (void)pressFundation:(NSString *)fundation Row:(NSInteger)row
{
    selectedDevice = [nowDevice objectAtIndex:row];
    [self sendRespondByFuctionName:fundation];
}

- (void)letViewNil
{
    self.myTVView = nil;
    self.myCurtainView = nil;
    self.myMBView = nil;
    self.myLightView = nil;
    self.myAirView = nil;
    self.mySTBView = nil;
    self.myDVDView = nil;
    self.myAMPView = nil;
    self.otherDeviceTableView = nil;
}

- (void)showFloorTable
{
    [self.myDeviceView removeFromSuperview];
    self.myDeviceView = nil;
    [self addSubview:self.floorTableView];
    [self.delegate showTitle:@"首页"];
    isFloorView = YES;
}

- (void)showRoomTable
{
    [self.myDeviceView removeFromSuperview];
    self.myDeviceView = nil;
    [self addSubview:self.floorTableView];
    [self.delegate showTitle:@"首页"];
}

- (void)showDeviceTable
{
    [nowView removeFromSuperview];
    [self letViewNil];
    [self.delegate showTitle:roomName];
    [self.myDeviceView showWithDeviceArray:nowDevice OtherArray:nowOtherDevice];
    [self addSubview:self.myDeviceView];
    [self.delegate showTabView];
    isFloorView = NO;
}

#pragma mark - 发送协议
- (void)sendRespondByFuctionName:(NSString *)fuctionName
{
    NSInteger deviceID = [[selectedDevice objectForKey:@"deviceId"] intValue];
    NSArray *deviceKey = [jsonDic objectForKey:@"DEVICE_KEY"];
    NSString *keyName;
    NSString *keyType;
    NSString *deviceType = [selectedDevice objectForKey:@"deviceType"];
    NSDictionary *deviceFuc = [functionList objectForKey:deviceType];
    NSDictionary *fucNameAndType = [deviceFuc objectForKey:fuctionName];
    keyName = [fucNameAndType objectForKey:@"name"];
    keyType = [fucNameAndType objectForKey:@"type"];
    
    NSDictionary *d;
    NSString *sensorId;
    for (d in deviceKey) {
        if([[d objectForKey:@"deviceId"]intValue] == deviceID
           && [[d objectForKey:@"keyName"] isEqualToString:keyName]
           && [[d objectForKey:@"keyType"] isEqualToString:keyType]){
            NSLog(@"设备ID:%ld",(long)deviceID);
            sensorId = [d objectForKey:@"sensorId"];
            //NSLog(@"%@",sensorId);
            if(sensorId != nil){
                NSString *sensorTable = [d objectForKey:@"sensorTable"];
                //NSLog(@"sensorTable:%@",sensorTable);
                [self sendMessageBySensorID:sensorId SensorArray:[jsonDic objectForKey:sensorTable]];
            }else{
                [self sendMessageBySensorID:sensorId SensorArray:nil];
            }
            return;
        }
    }
}

- (void)sendMessageBySensorID:(NSString *)sensorID SensorArray:(NSArray *)sensorArray
{
    if(sensorArray != nil){
        NSDictionary *dic;
        for (dic in sensorArray) {
            if([[dic objectForKey:@"sensorId"] isEqualToString:sensorID]){
                NSString *codeType = [dic objectForKey:@"codeType"];
                NSString *freqType = [dic objectForKey:@"freqType"];
                NSString *message1 = [NSString stringWithFormat:@"PT%@_%@-SEND-",codeType,freqType];
                self.sendMessage(message1, sensorID);
                return;
            }
        }
    }else{
        self.sendMessage(nil, nil);
    }
}


- (id) initWithFrame:(CGRect)frame andDic:(NSDictionary *)dic
{
    if(self = [super initWithFrame:frame]){
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *plistPath = [bundle pathForResource:@"FuctionList" ofType:@"plist"];
        functionList = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
        jsonDic = dic;
        isFloorView = YES;
        self.backgroundColor = BACKGROUND_COLOR;
        [self addSubview:self.floorTableView];
    }
    return self;
}

@end

@implementation cellState

@end
